<template>
	<view class="i-search" :style="{margin, background: bgColor, height}">
		<view class="flexss">
			<view class="search_inpt">
				<image src="../../static/images/search_black_icon.png" mode=""></image>
			</view>
			<input placeholder-class="placeholder-class" @focus="focus" @blur="blur" @confirm="confirm" @input="input" :style="{width}" v-model="keyWords"
				placeholder-style="font-size: 28rpx" class="input" :placeholder="placeholder" type="text">
		</view>
		<view class="close_input" v-if="keyWords" @click.stop="clear">
			<image src="../../static/images/close_input.png"></image>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import _ from 'lodash'
	import {
		ref,
		defineProps,
		defineEmits,
		watch
	} from 'vue';
	const keyWords = ref('')
	const props = defineProps({
		placeholder: {
			type: String,
			default: ''
		},
		margin: {
			type: String,
			default: '0 32rpx;'
		},
		bgColor: {
			type: String,
			default: '#F5F5F7'
		},
		modelValue: {
			type: String,
			default: ''
		},
		width: {
			type: String,
			default: '400rpx'
		},
		height: {
			type: String,
			default: '36px'
		},
	})
	const emit = defineEmits([
		'change',
		'update:modelValue',
		'clear',
		'blur',
		'focus'
	])

	const clear = () => {
		keyWords.value = ''
		emit('update:modelValue', '')
		emit('clear', '')
	}
	const confir = () => {
		emit('update:modelValue', keyWords.value)
		emit('change')
	}
	const input = () => {
		emit('update:modelValue', keyWords.value)
	}
	const blur = () => {
		setTimeout(() => {
			emit('blur')
		}, 100)

	}
	const focus = () => {
		emit('focus')
	}
	watch(() => props.modelValue, (val) => {
		// console.log(val, 'valval');
		if (val) {
			keyWords.value = val
		}
	}, {
		immediate: true
	})
	const confirm = _.debounce(confir, 400, { leading: true, trailing: false })
</script>

<style lang="scss" scoped>
	.i-search {
		@include flexRS;
		border-radius: 36rpx;
		padding: 2rpx 24rpx;
		position: relative;

		.search_inpt {
			width: 32rpx;
			height: 32rpx;
			margin-right: 16rpx;

			image {
				width: 32rpx;
				height: 32rpx;
			}
		}

		.flexss {
			@include flexR;
			width: 90%;
		}

		.close_input {
			width: 28rpx;
			height: 28rpx;
			@include flexR;
			position: absolute;
			z-index: 1;
			right: 24rpx;

			image {
				width: 28rpx;
				height: 28rpx;
			}
		}

		.input {
			font-size: 28rpx;
		}

	}
</style>